package com.longrise.common.base;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.GenericUtil;
import com.longrise.common.utils.NetUtil;


/**
 * Created by callxkj on 2017/2/21.
 * BaseFragment
 */

public abstract class BaseFragment<P extends BasePresenter> extends Fragment {
    public View mRootView;
    public P mPresenter;
    public Context mContext;
    public FragmentActivity mActivity;
    public RxManager mRxmanager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutResourse(container, savedInstanceState), container, false);
        }
        mPresenter = GenericUtil.getT(this, 0);
        mRxmanager = new RxManager();
        if (mPresenter != null && this instanceof BaseView) {
            mPresenter.mContext = this.getActivity();
            mPresenter.attachV(this);
            mPresenter.setRxManager(mRxmanager);
        }
        mContext = this.getActivity();
        mActivity = this.getActivity();
        initView();
        if (mPresenter != null && this instanceof BaseView) {
            mPresenter.init();
        }
        return mRootView;
    }

    /*********************
     * 子类实现
     *****************************/
    protected abstract int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState);

    public abstract void initView();

    /*******************************************************/

    public void showToast(String msg) {
        if (getContext() instanceof BaseActivity) {
            BaseActivity bAct = (BaseActivity) getActivity();
            bAct.showToast(msg);
        } else {
            DZZWTools.showToast(getContext(), msg, Toast.LENGTH_SHORT);
        }
    }

    public void showSnackBar(String msg) {
        BaseActivity activity = (BaseActivity) getActivity();
        activity.showSnakbar(msg);
    }

    protected boolean checkNetWorkEnable() {
        if (getContext() instanceof BaseActivity) {
            BaseActivity bAct = (BaseActivity) getContext();
            return bAct.checkNetWorkEnable();
        } else {
            //兼容未extends BaseActivity
            boolean enable = NetUtil.checkNetEnable();
            return enable;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachV();
        }
        if (mRxmanager != null) {
            mRxmanager.clear();
        }
    }
}
